<template>
  <el-dropdown trigger="click" @visible-change="handleDropdownVisible">
    <el-badge :value="unreadCount" :max="99" class="notification-badge">
      <el-icon :size="20" class="notification-icon">
        <Bell />
      </el-icon>
    </el-badge>
    
    <template #dropdown>
      <el-dropdown-menu class="notification-menu">
        <div class="notification-header">
          <h3>通知中心</h3>
          <el-button 
            type="text" 
            size="small"
            @click="markAllAsRead"
            :disabled="unreadCount === 0"
          >
            全部已读
          </el-button>
        </div>
        
        <el-scrollbar max-height="300px">
          <template v-if="notifications.length > 0">
            <div 
              v-for="notification in notifications" 
              :key="notification.id"
              class="notification-item"
              :class="{ unread: !notification.isRead }"
              @click="handleNotificationClick(notification)"
            >
              <div class="notification-content">
                <strong>{{ notification.title }}</strong>
                <p>{{ notification.content }}</p>
              </div>
              <div class="notification-time">
                {{ formatTime(notification.createdAt) }}
              </div>
            </div>
          </template>
          <div v-else class="empty-notifications">
            <el-empty description="暂无通知" :image-size="60" />
          </div>
        </el-scrollbar>
        
        <div class="notification-footer">
          <el-button 
            type="text" 
            size="small"
            @click="goToNotificationPage"
          >
            查看全部
          </el-button>
        </div>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Bell } from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const notifications = ref([])
const unreadCount = ref(0)

// 加载通知数据
const loadNotifications = async () => {
  const token = localStorage.getItem('token')
  if (!token) return;
  
  try {
    const response = await axios.get('/notifications', {
      params: {
        pageNum: 1,
        pageSize: 5
      },
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    
    if (response.data && response.data.data) {
      notifications.value = response.data.data.records || []
      updateUnreadCount()
    }
  } catch (error) {
    console.error('加载通知失败:', error)
    ElMessage.error('加载通知失败')
  }
}

// 更新未读计数
const updateUnreadCount = () => {
  unreadCount.value = notifications.value.filter(n => !n.isRead).length
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}

// 处理通知点击
const handleNotificationClick = async (notification) => {
  if (!notification.isRead) {
    try {
      const token = localStorage.getItem('token')
      await axios.put(`/notifications/${notification.id}/read`, {}, {
        headers: {
          Authorization: `Bearer ${token}`
        }
      })
      
      // 更新本地状态
      notification.isRead = true
      updateUnreadCount()
    } catch (error) {
      console.error('标记通知已读失败:', error)
    }
  }
  
  // 根据通知类型跳转
  if (notification.relatedType === 'LOST' && notification.relatedLostItemId) {
    router.push(`/lost/detail/${notification.relatedLostItemId}`)
  } else if (notification.relatedType === 'FOUND' && notification.relatedFoundItemId) {
    router.push(`/found/detail/${notification.relatedFoundItemId}`)
  }
}

// 标记所有通知为已读
const markAllAsRead = async () => {
  try {
    const token = localStorage.getItem('token')
    const unreadIds = notifications.value
      .filter(n => !n.isRead)
      .map(n => n.id)
    
    if (unreadIds.length === 0) return;
    
    // 批量标记为已读
    await Promise.all(
      unreadIds.map(id => 
        axios.put(`/notifications/${id}/read`, {}, {
          headers: {
            Authorization: `Bearer ${token}`
          }
        })
      )
    )
    
    // 更新本地状态
    notifications.value.forEach(n => {
      if (!n.isRead) n.isRead = true
    })
    unreadCount.value = 0
    ElMessage.success('全部标记为已读')
  } catch (error) {
    console.error('标记全部已读失败:', error)
    ElMessage.error('操作失败')
  }
}

const goToNotificationPage = () => {
  router.push('/user/dashboard/notifications')

}

// 当下拉框可见时加载通知
const handleDropdownVisible = (visible) => {
  if (visible) {
    loadNotifications()
  }
}

// 初始加载通知
onMounted(() => {
  loadNotifications()
})
</script>

<style scoped>
.notification-center {
  position: relative;
  cursor: pointer;
  margin-right: 10px;
}

.notification-badge {
  display: flex;
  align-items: center;
  justify-content: center;
}

.notification-icon {
  color: #666;
  transition: color 0.3s;
}

.notification-icon:hover {
  color: #42b983;
}

.notification-menu {
  width: 350px;
  padding: 0;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
}

.notification-header h3 {
  margin: 0;
  font-size: 16px;
}

.notification-item {
  padding: 12px 16px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background 0.2s;
}

.notification-item:hover {
  background-color: #f9f9f9;
}

.notification-item.unread {
  background-color: #f0f7ff;
}

.notification-content {
  margin-bottom: 8px;
}

.notification-content strong {
  color: #333;
  font-size: 14px;
}

.notification-content p {
  color: #666;
  font-size: 13px;
  margin: 5px 0 0;
  line-height: 1.4;
}

.notification-time {
  font-size: 12px;
  color: #999;
  text-align: right;
}

.empty-notifications {
  padding: 20px;
  text-align: center;
}

.notification-footer {
  padding: 8px 16px;
  border-top: 1px solid #eee;
  text-align: center;
}
</style>